// -----------------------------------------------------------------------
//  <copyright file="GetDictionaryItemNodeQuery.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-17 01:10</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Authorization;
using DaprPlus.DataDicts.Domain.Dtos;
using DaprPlus.DataDicts.Domain.Entities;
using DaprPlus.DataDicts.Domain.Specs;
using DaprPlus.MediatR;


namespace DaprPlus.DataDicts.Application.Queries;

[AuthConfig(typeof(DictionaryItem), ResourceAccessType.RoleLimit, "GetNode")]
public class GetDictionaryItemNodeQuery(string typeCode, string? keyword) : SingleQuery<DictionaryItemNodeOutDto[]>
{
    public string TypeCode { get; set; } = typeCode;
    public string? Keyword { get; set; } = keyword;
}

public class GetDictionaryItemNodeQueryHandler(IServiceProvider provider) 
    : IRequestHandler<GetDictionaryItemNodeQuery, DictionaryItemNodeOutDto[]>
{
    public async Task<DictionaryItemNodeOutDto[]> Handle(GetDictionaryItemNodeQuery request, CancellationToken cancellationToken)
    {
        var logger = provider.GetLogger<GetDictionaryItemNodeQueryHandler>();
        var queryRepository = provider.GetQueryRepository<DictionaryItem>();
        var spec = new DictionaryItemByTypeCodeAndKeywordSpec(request.TypeCode, request.Keyword)
            .And(new DictionaryItemUnlockedSpec());
        var nodes = await queryRepository.GetAllAsync<DictionaryItemNodeOutDto>(spec, cancellationToken);
        logger.LogInformation("获取字典项节点列表，字典类型代码：{TypeCode}，关键字：{Keyword}，结果数：{Count}",
            request.TypeCode, request.Keyword, nodes.Count);
        return [.. nodes];
    }
}
